package log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Log {

	public static int LOG_ERROR = 1 << 0;
	public static int LOG_EXCEPTION = 1 << 1;
	public static int LOG_INFO = 1 << 2;
	private static int currentlevel = LOG_ERROR | LOG_EXCEPTION | LOG_INFO;
	private static SimpleDateFormat dateFormat = new SimpleDateFormat(
			"yy/MM/dd HH:mm:ss");
	private static BufferedWriter stream;
	private static BufferedReader reader;

	private static BufferedWriter getStream() {
		if (stream == null)
			try {
				stream = new BufferedWriter(new OutputStreamWriter(
						new FileOutputStream(new File("log.log"), true)));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		return stream;
	}

	private static BufferedReader getReader() {
		if (reader == null)
			try {
				reader = new BufferedReader(new InputStreamReader(
						new FileInputStream(new File("log.log"))));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		return reader;
	}

	public static void set(int level, boolean enabled) {
		currentlevel = (enabled ? (currentlevel | level)
				: (currentlevel & ~level));
	}

	public static void log(int level, String message) {
		if ((currentlevel & level) > 0)
			try {
				System.out.println(time() + " - " + message);
				getStream().write(time() + " - " + message + "\n");
				getStream().flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}

	public static void close() throws IOException {
		getStream().close();
	}

	private static String time() {
		return dateFormat.format(Calendar.getInstance().getTime());
	}
	
	public static void printLog(PrintStream out) throws IOException {
		String str;
		while ((str = getReader().readLine()) != null) {
			out.println(str);
		}
	}

}
